using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using BMC.Models;

namespace BMC.Controllers;

public class BooksController : Controller
{
    private readonly BookDbContext db;
    public BooksController(){
        db= new BookDbContext();
    }
    // 查询
    public IActionResult Index(string key)
    {
        key=string.IsNullOrEmpty(key)?"":key.Trim();
        if(string.IsNullOrEmpty(key)){
           var list=db.Books.ToList();
           return View(list);
        }
        var a=db.Books.Where(x=>x.Title.Contains(key)).ToList();
        return View(a);
    }
    // 增加
    public IActionResult Add()
    {
        
        return View();
    }
    [HttpPost]
    public IActionResult Add(Book input)
    {
         db.Books.Add(input);
         db.SaveChanges();
        return RedirectToAction("Index");
    }
    // 删除
    public IActionResult Delete(int id)
    {
        var a=db.Books.FirstOrDefault(x=>x.Id==id);
        return View(a);
    }
    public IActionResult Deletes(int id)
    {
        var a=db.Books.FirstOrDefault(x=>x.Id==id);
        if(a==null){
            return NotFound();
        }
        db.Books.Remove(a);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    // 修改 
    public IActionResult Edit(int id)
    {
        var a=db.Books.FirstOrDefault(x=>x.Id==id);
        return View(a);
    }
    [HttpPost]
    public IActionResult Edit(Book input)
    {
        var a=db.Books.FirstOrDefault(x=>x.Id==input.Id);
        if(a==null){
            return NotFound();
        }
        a.Author=input.Author;
        a.Title=input.Title;
        a.Content=input.Content;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
}